<?php
/**
 * Created by PhpStorm.
 * User: hkui2015
 * Date: 2019/5/6
 * Time: 0:32
 * sleep被SIGINT,SIGCHLD 打断
 * ctrl+c 产生 SIGINT 打断sleep使子进程退出，子进程状态发生变化时，向父进程发送SIGCHLD信号打断sleep
 *
 */


$pid=pcntl_fork();
if($pid<0) exit(-1);

if($pid>0){
    //parent
    $parent_pid=posix_getpid();
    pcntl_signal(SIGINT,function ()use($parent_pid){
        echo PHP_EOL."parent:".$parent_pid."  want exit!".PHP_EOL;
        sleep(2);
    });
    pcntl_signal( SIGCHLD, function() use( $pid ) {
        echo "get son exit at ".microtime(true).PHP_EOL;
        pcntl_waitpid( $pid, $status, WNOHANG );
        $exit_status=pcntl_wifexited($status);
        echo "son exit status=".var_export($exit_status,1).PHP_EOL;

    } );

    $i=0;
    while($i<10){
        pcntl_signal_dispatch();
        echo "parent:".posix_getpid()."---".$i.PHP_EOL;
        sleep(1);

        $i++;
    }


}else{
    pcntl_signal(SIGINT,'sigfun');
    //son
    $i=0;
    while($i<5){
        pcntl_signal_dispatch();
        echo "son:".posix_getpid()."---".$i.PHP_EOL;
        sleep(1);
        if($i==3) {
           // posix_kill(posix_getpid(),SIGQUIT);//异常终止,pcntl_wifexited返回false
        }
        $i++;
    }
    echo "son ".posix_getpid()." exit at ".microtime(true).PHP_EOL;

}

function sigfun($signo){
    echo posix_getpid()." get exit signum: ".$signo.PHP_EOL;
    exit();
}